/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.common.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.mapper.BaseMapper;
import org.jbase.common.domain.BaseEntity;
import org.jbase.common.utils.message.Message;
import org.jbase.common.utils.message.MessageCode;

/**
 * Project: yxt_common <br/>
 * File: EntityMapperService.java <br/>
 * Class: org.jbase.common.service.EntityMapperService <br/>
 * Description: <描述类的功能>. <br/>
 * Copyright: Copyright (c) 2011 <br/>
 * Company: http://www.yxtsoft.com/ <br/>
 * Makedate: 2016年8月8日 上午11:43:16 <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
public abstract class EntityMapperService<T extends BaseEntity> extends BaseService {

	@SuppressWarnings("unchecked")
	private Class<T> clazz() {
		Class<T> entityClass = null;
		Type t = getClass().getGenericSuperclass();
		if (t instanceof ParameterizedType) {
			Type[] p = ((ParameterizedType) t).getActualTypeArguments();
			entityClass = (Class<T>) p[0];
		}
		return entityClass;
	}

	@SuppressWarnings("unchecked")
	private T entity() {
		T instance = null;
		Class<T> entityClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
				.getActualTypeArguments()[0];
		try {
			instance = entityClass.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return instance;
	};

	public abstract BaseMapper<T> dao();

	public Message<T> insert(T entity) {
		dao().insert(entity);
		Message<T> mess = new Message<>();
		mess.SetMessageCode(MessageCode.SUCCESS);
		mess.setSuccess(true);
		mess.setData(entity);
		return mess;
	}

	public Message<T> insert(T entity, boolean assignKey) {
		dao().insert(entity, assignKey);
		Message<T> mess = new Message<>();
		mess.SetMessageCode(MessageCode.SUCCESS);
		mess.setSuccess(true);
		mess.setData(entity);
		return mess;
	}

	public Message<T> insertReturnKey(T entity) {
		KeyHolder insertReturnKey = dao().insertReturnKey(entity);
		entity.setId(insertReturnKey.getInt());
		Message<T> message = new Message<T>();
		message.setSuccess(true);
		message.SetMessageCode(MessageCode.SUCCESS);
		message.setData(entity);
		return message;
	}

	public Message<T> updateById(T entity) {
		dao().updateById(entity);
		Message<T> message = new Message<T>();
		message.setSuccess(true);
		message.SetMessageCode(MessageCode.SUCCESS);
		message.setData(entity);
		return message;
	}

	public Message<T> updateTemplateById(T entity) {
		dao().updateById(entity);
		Message<T> message = new Message<T>();
		message.setSuccess(true);
		message.SetMessageCode(MessageCode.SUCCESS);
		message.setData(entity);
		return message;
	}

	public Message<Integer> deleteById(Object key) {
		int deleteById = dao().deleteById(key);
		Message<Integer> message = new Message<>();
		message.setSuccess(true);
		message.SetMessageCode(MessageCode.SUCCESS);
		message.setData(deleteById);
		return message;
	}

	public Message<Integer> deleteByIds(String ids) {
		if (ids.endsWith(","))
			ids = ids.substring(0, ids.length() - 1);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("table_name", sql.getNc().getTableName(clazz()));
		map.put("ids", ids);
		sql.update("common.deleteByIds", map);

		@SuppressWarnings("unchecked")
		Message<Integer> message = Message.fireSuccess();
		return message;
	}

	public Message<T> unique(Object key) {
		T unique = dao().unique(key);
		@SuppressWarnings("unchecked")
		Message<T> message = Message.fireSuccess();
		message.setData(unique);
		return message;
	}

	public Message<List<T>> all() {
		List<T> all = dao().all();
		@SuppressWarnings("unchecked")
		Message<List<T>> message = Message.fireSuccess();
		message.setData(all);
		return message;
	}

	public Message<List<T>> all(int start, int size) {
		List<T> all = dao().all(start, size);
		@SuppressWarnings("unchecked")
		Message<List<T>> message = Message.fireSuccess();
		message.setData(all);
		return message;
	}

	public long allCount() {
		return dao().allCount();
	}

	public List<T> template(T entity) {
		return dao().template(entity);
	}

	public List<T> template(T entity, int start, int size) {
		return template(entity, start, size);
	}

	public long templateCount(T entity) {
		return dao().templateCount(entity);
	}

	public List<T> execute(String sql, Object... args) {
		return dao().execute(sql, args);
	}

	public int executeUpdate(String sql, Object... args) {
		return dao().executeUpdate(sql, args);
	}

	public Message<T> saveOrUpdate(Map<String, Object> map) {
		String entityId = null;
		if (map.get("id") != null)
			entityId = map.get("id").toString();

		if (StringUtils.isBlank(entityId) || "0".equals(entityId.trim())) {
			return doInsert(map);
		} else {
			return doUpdate(map, entityId);
		}
	}

	public Message<T> doInsert(Map<String, Object> map) {
		T t = entity();
		t = map2entity(map, t);
		return this.insertReturnKey(t);
	}

	public Message<T> doUpdate(Map<String, Object> map, String entityId) {
		T t = dao().unique(entityId);
		t = map2entity(map, t);
		return this.updateById(t);
	}

	protected T map2entity(Map<String, Object> map, T t) {
		try {
			BeanUtils.populate(t, map);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;
	}

}
